<?php
namespace Admin\Controller;

use Think\Controller;
use Common\Controller\AdminController;
use Admin\Controller\SiteController;

/**
 * 单位信息管理
 * Class KefuController
 * @package Admin\Controller
 */
class KefuController extends AdminController {

    static $week = array("星期一" , "星期二", "星期三", "星期四", "星期五", "星期六", "星期天");

    /**
     * 系统管理 -> 系统管理 -> 建筑物信息维护 -> listview
     */
    public function index(){
        //获取搜索条件
        $filter = $this->fn_GenerateFilter();
        $where = $this->fn_GenerateWhereClause();
        $order = $this->fn_GenerateOrderBy();

        //分页信息
        $pageNum = intval(I("post.page"));
        $pageNum = $pageNum==0?1:$pageNum;
        $page = $this->fn_GetPageInfo($where, $pageNum);
        $this->assign("page", $page);

        //搜索出小区信息
        $limit = ($page['from']-1).",".$page['num'];
        $list = M("kefu")->where($where)->order($order)->limit($limit)->select();
        for($i=0; $i<count($list); $i++){
            $list[$i]["offset"] = $page['from']-1+$i;
        }
        $this->assign("list", $list);

        //设置community信息
        $this->assign("community", $this->fn_GetCommunityDict());

        //设置搜索条件
        $this->assign("filter", $filter);
        $this->assign("type", SiteController::fn_GetTypeDict());

        $this->display();
    }

    public function ajax_SearchMasterByName(){
        $h = array();
        $where = array("name"=>array("like", "%".I("get.name")."%"));
        $house = M("reziti_master")->where($where)->select();
        foreach ($house as $v){
            array_push($h, array("value"=>$v["name"], "data"=>$v));
        }
        $this->ajaxReturn(array('query'=>I("get.name"),'suggestions' => $h));
    }

    public function ajax_fenpeisf(){
        $oid = I("post.id");
        $kefu = M("kefu")->where(array("id"=>$oid))->find();
        if(!$kefu){
            $this->error("操作失败，订单不存在");
        }

        $member = M("reziti_member")->where(array("phone"=>$kefu['wechat_phone']))->find();
        if(!$member){
            $this->error("操作失败，会员信息不存在");
        }

        $data = I("post.data");
        $info = array(
            "master_name" => $data['name'],
            "master_phone" => $data['phone'],
            "date_kefu" => $data['date'],
            "utime" => time(),
        );
        $res = M("kefu")->where(array("id"=>$oid))->save($info);
        if(!$res){
            $this->error("操作失败，分配异常");
        }

        $this->success("操作成功");
    }

    /**
     * 发送模版消息
     */
    public function message_template_send($msg, $openid){
        $data = array(
            "touser"=> $openid,
            "template_id"=> "Sul86owhMyW-c6ZjoQTm6ChsiEXXrnvjiFTlvTiPYio",
            "url" => "",
            "topcolor" => '#aace3b',
            "data" => $msg,
        );
        vendor('WxPayPubHelper.WxPayPubHelper');
        $jsApi = new \wxPay\WxPayPubHelper\JsApi_pub();
        return $jsApi->message_template_send($data);
    }

    private function fn_GetCommunityList(){
        return M("community")->where()->select();
    }

    private function fn_GetCommunityDict(){
        $community = array();
        $list = M("community")->where()->select();
        for($i=0; $i<count($list); $i++){
            $community[$list[$i]["id"]] = $list[$i]["name"];
        }
        return $community;
    }

    /**
     * 建筑物信息维护 -> formview
     */
    public function detail(){
        //读取单位信息
        $dataId = I("get.id");
        $kefu = M("kefu")->where(array("id"=>$dataId))->find();
        $this->assign("kefu", $kefu);

        //查询条件
        $where = $this->fn_GenerateWhereClause();
        $order = $this->fn_GenerateOrderBy();
        $pageInfo = $this->fn_GetPageInfo($where);

        //页面信息
        $offset = intval(I("get.offset"));
        $nearby = $this->fn_FindNearbyItems($where, $order, $offset);
        $page = array_merge($pageInfo, $nearby);
        $this->assign("page", $page);

        // 设置上下文信息
        $context = $this->fn_GenerateContext($page);
        $this->assign("context", $context);
        $this->assign("weekOptions", json_encode(self::$week));

        //设置community信息
        $this->assign("type", SiteController::fn_GetTypeDict());
        $this->assign("typeOptions", json_encode(SiteController::fn_GetTypeList()));
        $this->display();
    }

    /**
     * 建筑物信息维护 -> 新增
     */
    public function add(){  //todo
        if(IS_POST){    //添加小区信息
            $data = array(
                "name" => I("post.name"),
                "qq" => I("post.qq"),
                "week" => I("post.week"),
                "type" => I("post.type"),
                "remarks" => I("post.remarks"),
                "cuser" => session("username"),
                "ctime" => date("Y/m/d")
            );
            $dataId = M("kefu")->add($data);
            if($dataId){
                header("Location:/admin/kefu/detail?id=".$dataId);
            }else{
                $this->error("系统错误，创建合同失败");
            }
        }

        //复制信息时处理流程
        if(I("get.id") && I("get.action"=="copy")){
            $house = M("kefu")->where(array("id"=>I("get.id")))->find();
            $this->assign("kefu", $house);
        }
        $this->assign("week", self::$week);

        //type
        $this->assign("type", SiteController::fn_GetTypeList());
        $this->display();
    }

    /**
     * 房屋自动补全搜索算法
     */
    public function ajax_SearchHouseByName(){
        $h = array();
        $where = array("name"=>array("like", "%".I("get.house")."%"));
        if(self::$u["role_code"]='4000'){ //小区管理员
            $com = $this->fn_GetCommunity(self::$u['username']);
            $where['community_id'] = array("in", $com);
        }

        $house = M("house")->where($where)->select();
        foreach ($house as $v){
            array_push($h, array("value"=>$v["name"], "data"=>$v));
        }
        $this->ajaxReturn(array('query'=>I("get.house"),'suggestions' => $h));
    }

    protected function fn_GenerateRepairNo(){
        $data = array("time"=>date("Y-m-d H:i:s"));
        $no = M("repair_no")->add($data);
        return "WX".$no;
    }

    /**
     * AJAX方法，在listview中进行批量删除信息
     */
    public function ajax_del(){

        $dataIds = I("post.info");
        if(count($dataIds)==0){
            $this->error("您还没有选中任何记录");
        }

        $map["id"] = array("in", $dataIds);
        $res = M("kefu")->where($map)->delete();
        # $res = $this->delete($map);
        if($res){
            $this->success("操作成功");
        }else{
            $this->error("系统错误");
        }
    }

    /**
     * AJAX方法，在formview中进行单条信息删除
     */
    public function ajax_del2(){
        //根据ID删除单位记录
        $id = I("post.id");
        $res = M("kefu")->where(array("id" => $id))->delete();
        # $res = $this->delete(['id' => $id]);
        if(!$res){
            $this->error("系统错误");
        }

        //分页信息
        $where = $this->fn_GenerateWhereClause();
        $order = $this->fn_GenerateOrderBy();
        $total = $this->fn_GetTotalItems($where);
        if($total==0){
            $this->success(null);
        }

        //计算下一条记录的offset
        $offset = intval(I("post.offset"));
        $offset = ($offset>=$total-1)?0:$offset;

        //获取下一记录的信息
        $nextItem = $this->fn_GetInfoByOffset($offset, $where, $order);
        $this->success($nextItem["id"]); //返回下一条记录的ID
    }

    /**
     * AJAX方法，通过ID来修改信息
     */
    public function ajax_UpdateInfoById(){
        $data = I("post.data");
        $dataId = I("post.id");
        $res = M("kefu")->where(array("id"=>$dataId))->save($data);
        if($res){
            $this->success("0k, 200");
        }else{
            $this->error("更新异常，请稍候再试");
        }
    }

    protected function fn_GetCommunity($username){
        $data = array();
        $where = array("admin_name"=>$username);
        $comm = M("community")->field("id")->where($where)->select();
        foreach ($comm as $item) {
            $data[] = $item['id'];
        }
        return $data;
    }

    /**
     *  辅助方法，通过$_POST的值来生成where查询条件
     */
    private function fn_GenerateWhereClause(){
        $where = array();
        if(self::$u["role_code"]=='4000'){ //小区管理员
            $com = $this->fn_GetCommunity(self::$u['username']);
            $where['community_id'] = array("in", $com);
        }

        if(I("request.value")){
            $where = array();
            if(I("request.field")=="community_id"){ //多表查询处理
                $cateIds = $this->fn_SelectCommunityByName(I("request.value"));
                $where[I("request.field")] = array("in", $cateIds);
            }else{
                $where[I("request.field")] = array("like", "%".I("request.value")."%");
            }
        }
        return $where;
    }

    private function fn_SelectCommunityByName($name){
        $where["name"] =  array("like", "%".$name."%");
        $result = M("community")->where($where)->field("id")->select();
        $cateIds = array();
        for($i=0; $i<count($result); $i++){
            array_push($cateIds, $result[$i]["id"]);
        }
        return $cateIds;
    }

    /**
     *  辅助方法，通过$_POST的值来生成order by子句
     */
    private function fn_GenerateOrderBy(){
        $order = "id desc";
        if(I("request.order_field") && I("request.order_sort")){
            $order = I("request.order_field") . " " . I("request.order_sort");
        }
        return $order;
    }

    /**
     *  辅助方法，通过$_POST的值来生成Filter (listview)
     */
    private function fn_GenerateFilter(){
        if(IS_POST){
            return array(
                "page" => I("post.page"),
                "field" => I("post.field"),
                "value" => I("post.value"),
                "order_field" => I("post.order_field"),
                "order_sort" => I("post.order_sort"),
            );
        }
        return array(
            "page" => 1,
            "order_field" => "id",
            "order_sort" => "desc",
        );
    }

    /**
     * 辅助方法，通过$_POST的值来生成Context (formvier)
     * @return array
     */
    private function fn_GenerateContext($page){
        return array(
            "id" => I("request.id"),
            "field" => I("request.field"),
            "value" => I("request.value"),
            "order_field" => I("request.order_field"),
            "order_sort" => I("request.order_sort"),
            "page" => I("request.page"),
            "offset" => I("request.offset"),
            "index" => I("get.offset")-($page["curPage"]-1)*$page["num"]+1
        );
    }

    /**
     * 辅助方法，通过where,order,offset来查询信息
     * @param $offset
     * @param $where
     * @param $order
     * @return mixed
     */
    private function fn_GetInfoByOffset($offset, $where, $order){
        $limit = $offset.",1";
        $res =  M("kefu")->field("id,name")->where($where)->order($order)->limit($limit)->select();
        if($res){
            return $res[0];
        }
        return array();
    }

    /**
     * 辅助方法，通过where, curpage, num来生成分页信息
     * @param $where
     * @param int $curPage
     * @param int $num
     * @return array
     */
    private function fn_GetPageInfo($where, $curPage=1, $num=15){
        $total = M("kefu")->where($where)->count();
        $totalPage = ceil($total/$num);
        $nextPage = $curPage==$totalPage?1:($curPage+1);
        $prevPage = $curPage==1?$totalPage:($curPage-1);
        $to = $curPage*$num;
        $res = array(
            "total" => $total,
            "num" => $num,
            "from" => (($curPage-1)*$num+1),
            "to" => $to>$total?$total:$to,
            "curPage" => $curPage,
            "nextPage" => $nextPage,
            "prevPage" => $prevPage
        );
        return $res;
    }

    /**
     * 辅助方法，通过where来统计总的信息数量
     * @param array $where
     * @return mixed
     */
    public function fn_GetTotalItems($where=array()){
        return M("kefu")->where($where)->count();
    }

    /**
     * 辅助方法，通过where, order, offset查询相邻两条数据
     * @param $where
     * @param $order
     * @param $offset
     * @return array
     */
    public function fn_FindNearbyItems($where, $order, $offset){
        $total = M("kefu")->where($where)->count();
        $prevOffset = $offset>0?$offset-1:$total-1;
        $nextOffset = $offset>=$total-1?0:$offset+1;
        $prevItem = $this->fn_GetInfoByOffset($prevOffset, $where, $order);
        $nextItem = $this->fn_GetInfoByOffset($nextOffset, $where, $order);
        return array(
            "prev" => array("id"=>$prevItem["id"],"offset"=>$prevOffset),
            "next" => array("id"=>$nextItem["id"],"offset"=>$nextOffset),
        );
    }

}